#include "mainwindow.h"
#include "msgprocessthread.h"
#include "ui_mainwindow.h"
#include "uimsg.h"
#include <QMutex>
#include <QQueue>
#include <QThread>
#include <QDebug>
#include <QWaitCondition>

QMutex g_MsgQueueMutex;
QWaitCondition g_condUiNotify;
QQueue<UiMsg> g_UiMsgQueue;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    qDebug() << " mainwindow ui thread " << QThread::currentThreadId();

    m_pPBStart = new QPushButton("start");
    m_pPBStop = new QPushButton("stop");
    m_pHBLGlobal = new QHBoxLayout;

    m_pHBLGlobal->addWidget(m_pPBStart,0,Qt::AlignHCenter);
    m_pHBLGlobal->addWidget(m_pPBStop,1,Qt::AlignHCenter);
    ui->centralWidget->setLayout(m_pHBLGlobal);

    m_pMsgProcessThread = new MsgProcessThread(&g_UiMsgQueue,&g_MsgQueueMutex,&g_condUiNotify);

    connect(m_pPBStart,SIGNAL(clicked()),this,SLOT(onBtnStartClicked()));
    connect(m_pPBStop,SIGNAL(clicked()),this,SLOT(onBtnStopClicked()));

    qRegisterMetaType<UiMsg>();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::onBtnStartClicked()
{
    static qint64 msgNo = 0;
    UiMsg uiMsg;

    if(!m_pMsgProcessThread->isRunning()){
        m_pMsgProcessThread->start();
    }

    uiMsg.msgType = 1;
    uiMsg.msgNo = msgNo;
    uiMsg.msgSendThreadId = QThread::currentThreadId();
    uiMsg.msgData = "message from ui";
    g_UiMsgQueue.push_back(uiMsg);

    g_condUiNotify.wakeAll();

    qDebug() << " insert message in queue for the first" << msgNo << " time ";

    msgNo ++;
}

void MainWindow::onBtnStopClicked()
{
    qDebug() << " request interrupt from ui thread ";

    //wake the message thread and exit the main loop
    g_condUiNotify.wakeAll();
    m_pMsgProcessThread->requestInterruption();

    //wait for a while util the message thread quited
    QThread::sleep(3);

    qDebug() << " message process thread is running " << m_pMsgProcessThread->isRunning();
}
